<template>
  <div>
    <el-form inline :model="sysUserQuery" ref="sysQueryFormRef">
      <el-form-item>
        <el-input placeholder="请输入关键字" v-model="sysUserQuery.keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="getUserList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="resetQueryForm(sysQuerFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button @click="openAddDialog" :icon="Plus" size="small" type="primary"
    >新增
    </el-button
    >
    <el-table
        :data="sysUserPage.list"
        style="width: 100%"
        v-loading="dataLoading"
        element-loading-text="拼命加载中..."
    >
      <el-table-column label="头像">
        <template #default="scope">
          <el-avatar shape="square" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户Id"/>
      <el-table-column prop="userName" label="用户名"/>
      <el-table-column prop="nickname" label="昵称"/>
      <el-table-column prop="sex" label="性别">
        <template #default="scope">
          {{ scope.row.sex == 0 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号"/>
      <el-table-column prop="status" label="状态"/>
      <el-table-column prop="remark" label="备注"/>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button @click="openUpdateDialog(scope.row)" type="warning" size="small" :icon="Edit">修改</el-button>
          <el-divider direction="vertical"/>
          <el-button @click="del(scope.row.userId)" type="danger" :icon="Delete" size="small" :disabled="scope.row.userName==='admin'">删除</el-button>
          <el-divider direction="vertical"/>
          <el-dropdown>
            <el-button type="primary" size="small" class="el-dropdown-link">
              更多
              <el-icon class="el-icon--right">
                <arrow-down/>
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="openGrantRole(scope.row.userId)" :disabled="scope.row.userName==='admin'">分配角色</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          size="small"
          background
          layout="prev, pager, next"
          :total="sysUserPage.total"
          v-model:page-size="sysUserQuery.pageSize"
          v-model:current-page="sysUserQuery.pageNum"
      />
    </div>
    <el-dialog
        v-model="dialogFormVisible"
        :title="dialogType === 0 ? '新增' : '修改'"
        width="500"
        @close="resetSysUserForm"
    >
      <el-form :model="sysUserForm" label-width="80px" :rules="rules" ref="ruleFormRef">
        <el-form-item label="头像" prop="avatar">
          <el-upload
              class="avatar-uploader"
              :action="avatarUploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
          >
            <img v-if="sysUserForm.avatar" :src="sysUserForm.avatar" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="sysUserForm.userName"/>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="sysUserForm.nickname"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="sysUserForm.password"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="sysUserForm.status">
            <el-radio :value="0">启用</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="sysUserForm.sex">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUser(ruleFormRef)"> 确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
        v-model="grantRoleDialogVisible"
        title="分配角色"
        width="500"
    >
      <div>
        <el-table @selection-change="handleSelectionChange" :data="rolePage.list" style="width: 100%" row-key="roleId"
                  ref="grantRoleRef">
          <el-table-column type="selection" width="55" :selectable="selectable"/>
          <el-table-column prop="roleId" label="编号" width="120"/>
          <el-table-column prop="roleName" label="权限名" width="120"/>
          <el-table-column prop="roleCode" label="角色标识"/>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="grantRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGrant">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {reactive, ref, onMounted, watch} from "vue";
import {ElMessage, ElMessageBox,} from "element-plus";
import {Plus, Search, Delete, Edit, ArrowDown} from "@element-plus/icons-vue";
import {reqCreateUser, reqDeleteUserById, reqGetUserPage, reqUpdateUser} from "@/api/system/user.js";
import {reqGetRolePageList, reqGetSysRoleListByUserId, reqUserGrantRole} from "@/api/system/role.js";
import {avatarUploadUrl} from '@/util/uploade.js'

let sysUserPage = reactive({
  total: 0,
  list: [],
  pageNum: 0
})
let dialogFormVisible = ref();
let dialogType = ref(0); //0新增，1修改
let dataLoading = ref(true);
let grantRoleDialogVisible = ref(false)
let ruleFormRef = ref()
let sysQueryFormRef = ref()
let sysUserQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: "",
  status: -1,
  phone: "",
});

let sysUserForm = reactive({
  userId: "",
  userName: "",
  nickname: "",
  password: "",
  sex: 0,
  status: 0,
  remark: "",
  avatar: "",
  phone: "",
});

let sysRoleQuery = reactive({
  keywords: "",
  pageNum: 1,
  pageSize: 20,
});
let grantRoleRef = ref()
let grantRoleForm = reactive({
  roleIdList: [],
  userId: ""
})
let rolePage = reactive({
  total: 0,
  list: [],
  pageNum: 1
})
let rules = reactive({
  userName: [{required: true, message: "请输入用户名", trigger: "blur",},],
  password: [{required: true, message: "请输入密码", trigger: "blur",},],
  nickName: [{required: true, message: "请输入昵称", trigger: "blur",},],
  phone: [{required: true, message: "请输入手机号", trigger: "blur",},]
})

let handleAvatarSuccess = (res) => {
  sysUserForm.avatar = res
}
//不能授予超级管理员角色
const selectable = (row) => row.roleCode!=="admin"
let resetSysUserForm = () => {
  Object.assign(sysUserForm, {
    userId: "",
    userName: "",
    nickname: "",
    password: "",
    sex: 0,
    status: 0,
    remark: "",
    avatar: "",
    phone: "",
  });
  dialogType.value  = 0;
};
function getUserList() {
  reqGetUserPage(sysUserQuery).then((res) => {
    Object.assign(sysUserPage, res.data);
    dataLoading.value = false;
  });
}

const resetQueryForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

function openAddDialog() {
  dialogType.value = 0;
  dialogFormVisible.value = true;
}

//将选中的行的roleId放入roleIds中
let handleSelectionChange = (val) => {
  grantRoleForm.roleIdList = val.map(item => item.roleId)
}
let submitGrant = () => {
  if (grantRoleForm.roleIdList.length > 0) {
    reqUserGrantRole(grantRoleForm)
  }
  //重置
  Object.assign(grantRoleForm, {
    roleIdList: [],
    userId: ""
  })
  grantRoleDialogVisible.value = false
}
//初始化：获取角色列表，并默认选中当前用户已有的角色
let openGrantRole = async (userId) => {
  grantRoleForm.userId = userId
  let res = await reqGetRolePageList(sysRoleQuery)
  rolePage.list = res.data.list
  grantRoleDialogVisible.value = true
  let res2 = await reqGetSysRoleListByUserId(userId)
  grantRoleForm.grantRoleForm = res2.data.map(item => item.roleId)
  //默认选中
  rolePage.list.forEach(item => {
    if (grantRoleForm.grantRoleForm.includes(item.roleId)) {
      grantRoleRef.value.toggleRowSelection(item, true);
    }
  })
}

function openUpdateDialog(user) {
  Object.assign(sysUserForm, user);
  dialogType.value = 1;
  dialogFormVisible.value = true;
}

async function submitUser(formEl) {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialogType.value === 0) {
        await reqCreateUser(sysUserForm);
      } else await reqUpdateUser(sysUserForm);
      await getUserList();
      dialogFormVisible.value = false;
    } else {
      console.log('error submit!', fields)
    }
  })
}

function del(userId) {
  ElMessageBox.confirm("删除之后无法恢复，请确认是否删除？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        reqDeleteUserById(userId).then(() => {
          ElMessage({
            message: "删除成功！",
            type: "success",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！",
        })
      })
}

onMounted(() => {
  getUserList();
});

watch([() => sysUserQuery.pageNum, () => sysUserQuery.pageSize], () => {
  getUserList()
})
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
